package com.jxb.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.jxb.ExceptionUtil;
import com.jxb.api.OrderFeignService;

import lombok.extern.slf4j.Slf4j;

/**
 * 类注释
 *
 * @author jiaobo
 * @date Created in 2024/10/13 19:20
 **/
@RestController
@Slf4j
public class HelloController {

    @Resource
    private RestTemplate restTemplate;

    private static final String RESOURCE_NAME = "HelloWorld";

    private AtomicInteger atomicInteger = new AtomicInteger();

    @RequestMapping(value = "/hello")
    public String hello() {
        try(Entry entry = SphU.entry(RESOURCE_NAME)) {
            // 被保护的逻辑
            log.info("hello world");
            return "hello world";
        } catch (BlockException e) {
            // 处理被流控的逻辑
            log.info("blocked!");
            return "被流控了";
        }
    }

    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        //设置保护的资源
        flowRule.setResource(RESOURCE_NAME);
        //设置流控规则QPS
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //设置保护的阈值
        flowRule.setCount(1);
        rules.add(flowRule);
        //加载配置好的规则
        FlowRuleManager.loadRules(rules);
    }

    @SentinelResource(value = RESOURCE_NAME,blockHandler = "handleException",fallback = "fallbackException")
    @RequestMapping("/hello2")
    public String hello2() {
        //int i = 1 / 0;
        return "helloworld";
    }

    public String handleException(BlockException ex){
        return "被流控了";
    }
    public String fallbackException(Throwable t){
        return "被异常降级了";
    }

    @Autowired
    OrderFeignService orderFeignService;

    @RequestMapping(value = "/findOrderByUserId/{id}")
    @SentinelResource(value = "findOrderByUserId",
            fallback = "fallback",fallbackClass = ExceptionUtil.class,
            blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class
    )
    public Object  findOrderByUserId(@PathVariable("id") Integer id) {

        //模拟响应耗时-并发数不超过指定阈值
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //ribbon实现
        // String url = "http://mall-order/order/findOrderByUserId/"+id;
        // Object result = restTemplate.getForObject(url,Object.class);
        //feign调用
        String result = orderFeignService.findOrderByUserId(id);
        if(id==4){
            throw new IllegalArgumentException("非法参数异常");
        }

        return result;
    }


    @RequestMapping(value = "/user/info/{id}")
    @SentinelResource(value = "userInfo",
            fallback = "fallback",fallbackClass = ExceptionUtil.class,
            blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class
    )
    public Object userInfo(@PathVariable("id") Integer id) {
        String url = "http://mall-order/order/findOrderByUserId/"+id;
        Object result = restTemplate.getForObject(url,Object.class);
        if(id==4){
            throw new IllegalArgumentException("非法参数异常");
        }

        return "userInfo";
    }

    @SentinelResource(value = "test",
            fallback = "fallback",fallbackClass = ExceptionUtil.class,
            blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class
    )
    @RequestMapping("/test")
    public String test() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "test ====================== ";
    }


    @SentinelResource(value = "test2",
            fallback = "fallback",fallbackClass = ExceptionUtil.class,
            blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class
    )
    @RequestMapping("/test2")
    public String test2() {
        atomicInteger.getAndIncrement();
        //模拟异常比列
        if (atomicInteger.get() % 2 == 0) {
            int i = 1/0;
        }
        return "test2 ====================== ";
    }

    @SentinelResource(value = "test3",
            fallback = "fallback",fallbackClass = ExceptionUtil.class,
            blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class
    )
    @RequestMapping("/test3/{id}")
    public String test3(@PathVariable("id") Integer id) {
        return "test3 ====================== ";
    }

}
